package com.sky.cqculture.Contraller;

import com.sky.cqculture.pojo.Category;
import com.sky.cqculture.pojo.Result;
import com.sky.cqculture.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/categories")
public class CategoryController {
    
    @Autowired
    private CategoryService categoryService;
    
    /**
     * 获取所有分类
     * GET /api/categories
     */
    @GetMapping
    public Result getAllCategories() {
        List<Category> categories = categoryService.findAllCategories();
        return Result.success(categories);
    }
    
    /**
     * 根据ID获取分类
     * GET /api/categories/{id}
     */
    @GetMapping("/{id}")
    public Result getCategoryById(@PathVariable Integer id) {
        Category category = categoryService.findCategoryById(id);
        if (category == null) {
            return Result.error("分类不存在");
        }
        return Result.success(category);
    }
    
    /**
     * 添加分类
     * POST /api/categories
     */
    @PostMapping
    public Result addCategory(@RequestBody Category category) {
        if (category.getName() == null || category.getName().trim().isEmpty()) {
            return Result.error("分类名称不能为空");
        }
        categoryService.addCategory(category);
        return Result.success("添加分类成功");
    }
    
    /**
     * 更新分类
     * PUT /api/categories
     */
    @PutMapping
    public Result updateCategory(@RequestBody Category category) {
        if (category.getId() == null) {
            return Result.error("分类ID不能为空");
        }
        if (category.getName() == null || category.getName().trim().isEmpty()) {
            return Result.error("分类名称不能为空");
        }
        categoryService.updateCategory(category);
        return Result.success("更新分类成功");
    }
    
    /**
     * 删除分类
     * DELETE /api/categories/{id}
     */
    @DeleteMapping("/{id}")
    public Result deleteCategory(@PathVariable Integer id) {
        categoryService.deleteCategoryById(id);
        return Result.success("删除分类成功");
    }
}